package com.cndw.kungfu.model.goods;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cndw.commons.util.BlankUtils;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.domain.Goods;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.GoodsSuite;
import com.cndw.kungfu.domain.GoodsSuiteProp;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.goods.domain.SubPops;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.goodsvo.GoodsSuitePropVO;
import com.cndw.kungfu.vo.goodsvo.GoodsSuiteVO;
import com.cndw.kungfu.vo.goodsvo.GoodsVO;
import com.cndw.kungfu.vo.goodsvo.SubPopsVO;

@Component
public class GoodsServer {

	@Autowired
	private GoodsManager goodsManager;

	/**
	 * 获取背包
	 * 
	 * @param playerId
	 * @return
	 */
	public PlayerBoxs getPlayerBoxs(long playerId) {
		Player player = Context.getPlayerServer().getByPlayerId(playerId);

		if (player != null) {
			return player.getPlayerBoxs();
		}
		return null;
	}

	/**
	 * 初始化我的背包
	 * 
	 * @param playerId
	 * @return
	 */
	public PlayerBoxs initBoxsFromDb(long playerId, int boxsGirds, int holdGrids) {
		return goodsManager.initBoxsFromDb(playerId, boxsGirds, holdGrids);
	}

	/**
	 * 获取装备模型
	 * 
	 * @param goodsId
	 * @return
	 */
	public GoodsMode getModeById(int goodsId) {
		return Context.getCacheCenter().getGoodsModeById(goodsId);
	}

	/**
	 * 获取装备的套装属性
	 * 
	 * @param goodsList
	 */
	public Map<Integer, GoodsSuiteVO> getGoodsSuites(long playerId) {
		Map<Integer, GoodsSuiteVO> suiteMap = new HashMap<Integer, GoodsSuiteVO>();
		PlayerBoxs playerBoxs = getPlayerBoxs(playerId);
		if (playerBoxs == null) {
			return suiteMap;
		}

		Collection<Goods> goodsList = playerBoxs.getEquipList();
		for (Goods goods : goodsList) {

			// 判断物品是否是装备，是否是套装，是否有等级
			GoodsMode goodsMode = Context.getGoodsServer().getModeById(goods.getGoodsId());
			if (goodsMode == null) {
				continue;
			}
			if (goodsMode.isEquiq() && goodsMode.getClassId() != 0) {

				if (suiteMap.containsKey(goodsMode.getClassId())) {
					GoodsSuiteVO suiteVO = suiteMap.get(goodsMode.getClassId());

					Object[] config = suiteVO.getGoods().get(goodsMode.getGoodsId());
					if (!BlankUtils.isBlank(config) && !Boolean.valueOf(config[1].toString())) {
						config[1] = true;
						for (GoodsSuitePropVO propVO : suiteVO.getProps().values()) {
							propVO.setHasCounts(propVO.getHasCounts() + 1);
						}
					}
				} else {

					GoodsSuite suite = Context.getCacheCenter().getGoodsSuiteById(goodsMode.getClassId());
					if (suite == null) {
						continue;
					}
					GoodsSuiteVO suiteVO = new GoodsSuiteVO();
					suiteVO.setId(suite.getId());
					suiteVO.setName(suite.getName());

					for (Integer goodsId : suite.getGoods().keySet()) {
						GoodsMode mode = Context.getGoodsServer().getModeById(goodsId);
						suiteVO.getGoods().put(goodsId, new Object[] { mode.getName(), goodsMode.getGoodsId() == goodsId.intValue() });
					}

					for (GoodsSuiteProp prop : suite.getProps()) {
						GoodsSuitePropVO propVO = prop.toGoodsSuitePropVO();
						propVO.setHasCounts(1);
						suiteVO.getProps().put(propVO.getConditions(), propVO);
					}

					suiteMap.put(goodsMode.getClassId(), suiteVO);
				}
			}
		}

		return suiteMap;
	}

	/**
	 * 发道具
	 * 
	 * @param playerId
	 *            角色id
	 * @param goodsId
	 *            物品id
	 * @param num
	 *            数量
	 * @param luck
	 *            是否幸运
	 */
	private void giveGoodsOrEquiq(long playerId, int goodsId, int num, boolean luck, int binding) {

		GoodsMode goodsMode = getModeById(goodsId);
		if (goodsMode == null) {
			return;
		}
		if (goodsMode.isEquiq()) {
			goodsManager.addEquip(playerId, goodsId, num, luck, binding);
		} else {
			goodsManager.addGoods(playerId, goodsId, num, binding);
		}

		if (goodsMode.isTaskItem()) {
			Context.getTaskServer().sparkOverseeTask(playerId, goodsId);
		}
	}

	public void giveGoods(long playerId, int goodsId, int num) {
		giveGoodsOrEquiq(playerId, goodsId, num, false, 0);
	}

	public void giveGoodsBing(long playerId, int goodsId, int num, int bing) {
		giveGoodsOrEquiq(playerId, goodsId, num, false, bing);
	}
	
	@Deprecated
	public void giveGoodsLuck(long playerId, int goodsId, int num, boolean luck) {
		giveGoodsOrEquiq(playerId, goodsId, num, luck, 0);
	}

	/**
	 * 设置装备等级
	 */
	public void upgradeGoodsLevel(Goods goods) {
		goodsManager.upgradeGoodsLevel(goods);
	}

	/**
	 * 检查礼包需要的背包格子.一半情况下只判断礼包条数即可
	 * 
	 * @param subPopsList
	 * @return
	 */
	public int checkSubPopsBlack(List<SubPops> subPopsList) {
		int needSize = 0;
		if (subPopsList != null && !subPopsList.isEmpty()) {
			for (SubPops e : subPopsList) {
				if (e.getGoodsId() > 0) {
					GoodsMode goodsMode = getModeById(e.getGoodsId());
					if (goodsMode != null) {
						needSize += NumberProcesser.ceil(e.getNum(), goodsMode.getMaxStack());
					}
				}
			}
		}
		return needSize;
	}

	public void giveSubPops(List<SubPops> subPopsList, Player player, StringBuffer logSB,int eventId) {
		if (subPopsList == null || subPopsList.isEmpty()) {
			return;
		}
		for (SubPops e : subPopsList) {
			if (e.getGoodsId() > 0) {
				GoodsMode goodsMode = getModeById(e.getGoodsId());
				if (goodsMode != null) {
					giveGoodsBing(player.getPlayerId(), e.getGoodsId(), e.getNum(),e.getBind());
					if (logSB != null) {
						logSB.append("|" + goodsMode.getName() + ":" + e.getNum());
					}
				}else{
					LogUtil.getMain().error("goodsId "+e.getGoodsId());
				}
		
			}
			if (e.getAsset() > 0) {
				player.alterAsset(e.getAsset());
				if (logSB != null) {
					logSB.append("|银两:" + e.getAsset());
				}
			}
			if (e.getExp() > 0) {
				player.alterExp(e.getExp());
				if (logSB != null) {
					logSB.append("|经验:" + e.getExp());
				}
			}
			
			
			if (e.getGold() > 0 || e.getGoldBing() >0) {				
				player.receiveGold(e.getGold());
				player.receiveGoldBind(e.getGoldBing());
				if (logSB != null) {
					logSB.append("|元宝:" +( e.getGold()+e.getGoldBing()));
				}
				LogServer.gotEventLog(player.getPlayerId(), e.getGold()+e.getGoldBing(), eventId);
				if (eventId == 0 ) {
					LogUtil.getMain().info("no type got gold "+e.getGold()+" | "+e.getGoldBing() +" playerId:"+player.getPlayerId());
					//new Throwable("playerId:"+player.getPlayerId() +" gold:"+e.getGold()).printStackTrace();
				}
			}
		}
	}
	public void giveSubPops(List<SubPops> subPopsList, Player player, StringBuffer logSB){
		giveSubPops(subPopsList, player, logSB,0);
	}

	/**
	 * 发放礼包内容到玩家
	 * 
	 * @param subPopsList
	 * @param player
	 */
	public void giveSubPops(List<SubPops> subPopsList, Player player) {
		giveSubPops(subPopsList, player, null);
	}

	/**
	 * 生成礼包的物品vo
	 * 
	 * @param subPopsList
	 * @return
	 */
	public SubPopsVO makeAwards(List<SubPops> subPopsList) {
		SubPopsVO vo = new SubPopsVO();
		List<GoodsVO> tempAwards = null;
		if (subPopsList != null) {
			tempAwards = new ArrayList<GoodsVO>();
			for (SubPops e : subPopsList) {
				if (e.getGoodsId() >0 ) {
					GoodsMode goodsMode = getModeById(e.getGoodsId());
					if (goodsMode == null) {
						continue;
					}
					GoodsVO goodsVO = new GoodsVO(goodsMode);
					if (goodsVO != null) {
						goodsVO.setStackNum(e.getNum());
						if (e.getBind() >0 ) {
							goodsVO.setBinding(1);
						}
					}
					tempAwards.add(goodsVO);
				}
				if (e.getAsset() >0) {
					vo.alterAsset(e.getAsset());
				}
				if (e.getExp() >0 ) {
					vo.alterExp(e.getExp());
				}

			}
		}
		vo.setGoodsList(tempAwards);
		return vo;
	}

	/**
	 * 计算装备星际追加值，返回数字值分别为 [命中hit，闪避dodge，暴击crit，韧性tough]
	 * 
	 * @return
	 */
	public int[] calculateGoodsStar(GoodsMode mode, int level) {

		int[] value = { 0, 0, 0, 0 };

		if (level >= 5) {
			int index = -1;
			switch (mode.getGoodTypeId()) {
			case 206: // 手部
			case 209: // 戒指
				index = 0; // hit
				break;
			case 204: // 脚部
			case 208: // 腰部
				index = 1; // dodge
				break;
			case 207: // 首饰
			case 205: // 武器
				index = 2; // crit
				break;
			case 201: // 头部
			case 202: // 上身
				index = 3; // tough
				break;
			}

			if (index < 0) {
				return value;
			}

			int v = mode.getPlayerLevel() * level * level * 10 / 6;

			v = v > 0 ? v : 1;

			value[index] = v;

			return value;

		} else {
			return value;
		}
	}
	
	/**
	 * 使用聚宝盆
	 * 
	 * @param player
	 * @param asset
	 */
	public boolean buyAsset(Player player, long asset) {
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(ConstantsModel.cornucopiaId);
		int count = (int) ((asset - player.getAsset()) / (long) goodsMode.getValueB() + 1); // 需要购买聚宝盆的数量
		int gold = (int) (goodsMode.getGold() * count);
		if (player.getGoldAll() < gold) {
			return false;
		} else if (gold <= 0) {
			return false;// 没有价格不给购买
		}
		if (gold <= 0) {
			return false;
		}

		int addAsset = (int) (goodsMode.getValueB() * count);
		player.alterGoldAll(-gold); // 扣金币
		//player.alterVipScore(gold / 5); // 增加商城积分
		player.alterAsset(addAsset); // 给银两
		player.commitSync();// 提交同步

		LogServer.recordLog(player, ConstantsLog.goods, 70017, Constants.PAY_GOLD, goodsMode.getName(), goodsMode.getGoodsId(), count, gold,
				player.getVipScore(), addAsset);
		LogServer.costLog(player.getPlayerId(), Constants.PAY_GOLD, gold, 0, player.getVipScore(), ConstantsModel.cornucopiaId, count);
		return true;
	}
	/**
	 * 注意检查业务逻辑里面本身需要消耗元宝
	 * @param player
	 * @param goodsId
	 * @param count
	 * @return
	 */
	public boolean buyStore(Player player,int goodsId,int count){
		return buyStore(player, goodsId, count,0);
	}
	
	/**
	 * 自动购买
	 * 注意检查业务逻辑里面本身需要消耗元宝
	 * @param player
	 * @param asset
	 */
	public boolean buyStore(Player player, int goodsId, int count,int otherCost) {
		if (otherCost < 0) {
			return false;
		}
		int haveCount = player.getPlayerBoxs().getStackNum(goodsId);
		count = count - haveCount;
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
		int gold = (int) (goodsMode.getGold() * count);
		if (player.getGoldAll() < gold + otherCost) {
			return false;
		} else if (gold <= 0) {
			return false;// 没有价格不给购买
		}

		player.alterGoldAll(-gold); // 扣金币
		//player.alterVipScore(gold / 5); // 增加商城积分
		if (haveCount > 0) {
			player.getPlayerBoxs().costGoods(goodsId, haveCount);
		}
		player.commitSync();// 提交同步

		LogServer.recordLog(player, ConstantsLog.goods, 70017, Constants.PAY_GOLD, goodsMode.getName(), goodsMode.getGoodsId(), count, gold,
				player.getVipScore(), 0);
		LogServer.costLog(player.getPlayerId(), Constants.PAY_GOLD, gold, 0, player.getVipScore(), goodsId, count);
		return true;
	}
}
